<!-- IT云化资源配置 -->
<template>
	<div>
		<el-tabs v-model="activeName" @tab-change="handleClick">
			<el-tab-pane label="未确认" name="unconfirmed">
				<yd-form :options="unConFormOptions" :model="queryUnconfirmedParams" :btns="unConFormBtns"></yd-form>
				<!-- 数据列表 -->
				<YdTable
					:formData="queryUnconfirmedParams"
					:tableConfig="tableUnconfirmedConfig"
					:tableData="tableUnconfirmedData"
					@sizeChangeHandler="getUnconfirmedList"
					@currentChangeHandler="getUnconfirmedList"
					@sortChangeHandler="getUnconfirmedList"
					@selectionChangeHandler="handlerSelectionChange"
				>
				</YdTable>
			</el-tab-pane>
			<el-tab-pane label="已确认" name="confirmed">
				<yd-form :options="conFormOptions" :model="queryConfirmedParams" :btns="conFormBtns"></yd-form>
				<!-- 数据列表 -->
				<YdTable
					:formData="queryConfirmedParams"
					:tableConfig="tableConfirmedConfig"
					:tableData="tableConfirmedData"
					@sizeChangeHandler="queryConfirmedList"
					@currentChangeHandler="queryConfirmedList"
					@sortChangeHandler="queryConfirmedList"
				>
				</YdTable>
			</el-tab-pane>
			<el-tab-pane label="黑名单" name="blacklist">
				<yd-form :options="blackFormOptions" :model="queryBlacklistParams" :btns="blackFormBtns"></yd-form>
				<!-- 数据列表 -->
				<YdTable
					:formData="queryBlacklistParams"
					:tableConfig="tableBlacklistConfig"
					:tableData="tableBlacklistData"
					@sizeChangeHandler="getBlacklistList"
					@currentChangeHandler="getBlacklistList"
					@sortChangeHandler="getBlacklistList"
				>
				</YdTable>
			</el-tab-pane>
		</el-tabs>

		<!-- 确认对话框 -->
		<el-dialog v-model="open" :title="title" width="500px" append-to-body center>
			<el-form ref="conForm" :model="form" :rules="rules" label-width="120px">
				<el-form-item label="URL" prop="url">
					<el-input v-model="form.url" :disabled="title === '再次确认'" type="textarea" :rows="3" placeholder="请输入URL" @input="change" />
				</el-form-item>
				<el-form-item label="所属系统" prop="system">
					<el-select v-model="form.system" value-key="id" placeholder="请选择" @change="handleSelectChange">
						<el-option v-for="item in systemOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="所属网端" prop="segmentId">
					<el-select v-model="form.segmentId" :disabled="segmentOptionsDisabled" multiple :multiple-limit="2" placeholder="请选择">
						<el-option v-for="item in segmentOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer class="dialog-footer">
				<el-button type="primary" :loading="unconfirmedLoading" @click="submitConfirmResourceForm">确 定</el-button>
				<el-button :loading="unconfirmedLoading" @click="cancel">取 消</el-button>
			</template>
		</el-dialog>

		<!-- 添加或修改参数配置对话框 -->
		<el-dialog v-model="addBlackOpen" :title="addBlackTitle" width="500px" append-to-body center>
			<el-form ref="addBlackFormRef" :model="addBlackForm" :rules="rules" label-width="120px">
				<el-form-item label="URL" prop="url">
					<el-input v-model="addBlackForm.url" type="textarea" placeholder="请输入URL" @input="change" />
				</el-form-item>
			</el-form>
			<template #footer class="dialog-footer">
				<el-button type="primary" :loading="unconfirmedLoading" @click="submitAddBlackForm">确 定</el-button>
			</template>
		</el-dialog>

		<!-- 添加或修改参数配置对话框 -->
		<el-dialog v-model="urlListOpen" title="URL前缀" width="900px" append-to-body center>
			<!-- 数据列表 -->
			<YdTable
				:formData="queryUrlDataParams"
				:tableConfig="tableUrlDataConfig"
				:tableData="tableUrlData"
				@sizeChangeHandler="querytUrlMappingPage"
				@currentChangeHandler="querytUrlMappingPage"
				@sortChangeHandler="querytUrlMappingPage"
			>
			</YdTable>
			<template #footer class="dialog-footer">
				<el-button @click="urlListOpenCancel">取 消</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="ItCloudResource" lang="ts">
import {
	getUnconfirmed,
	getConfirmedList,
	getBlackList,
	confirmResource,
	getUrlMappingPage,
	addBlackList,
	addBlackListBatch,
	confirmResourceAgain,
	deleteConfirmedResource,
	deleteBlackList,
} from '@/api/management/resourceManage/itCloudResource';
import { queryAppSystemOptions, querySegmentOptions } from '@/api/search/searchOptions';
import { ref, reactive, toRefs, onMounted } from 'vue';
import useCurrentInstance from '@/utils/useCurrentInstance';

const { proxy } = useCurrentInstance();

const unconfirmedLoading = ref(false);
const open = ref(false);
const type = ref(0);
const urlListOpen = ref(false);
const addBlackOpen = ref(false);
const title = ref('');
const addBlackTitle = ref('');
// 表单校验
const rules = ref({
	url: [{ required: true, message: 'URL不能为空', trigger: 'blur' }],
	system: [{ required: true, message: '系统不能为空', trigger: 'change' }],
	segmentId: [{ required: true, message: '网端不能为空', trigger: 'change' }],
});
// 表单参数
const data = reactive<anyObj>({
	form: {},
});
const { form } = toRefs(data);
let addBlackForm = reactive<anyObj>({});
const activeName = ref('unconfirmed');
//未确认列表选中
const unconfirmedListSelect = ref([]);
// 未确认列表配置
let tableUnconfirmedConfig = reactive({
	url: getUnconfirmed,
	columns: [
		{
			label: 'URL前缀',
			prop: 'prefixUrl',
			showOverFlowToolTip: true,
		},
		{
			label: '统计数',
			prop: 'urlCount',
			operation: [
				{
					text: undefined,
					rowKey: 'urlCount',
					handler: (scope: anyObj) => handleLookUrlMapping(scope.row),
				},
			],
		},
		{
			label: '操作',
			prop: '',
			operation: [
				{
					text: '确认',
					handler: (scope: anyObj) => handleConfirmResource(scope.row, 0),
					permi: ['system:itCloud:confirm'],
				},
			],
		},
	],
	// 工具栏
	toolBar: [
		{
			name: '加入黑名单',
			icon: 'yd-icon-plus',
			disable: 'multiple',
			handler: () => handlerAddBlack(),
			permi: ['system:itCloud:addBlack'],
		},
	],
	// 开启复选框
	enableSelection: true,
	// 开启分页
	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	// 加载层
	loading: true,
});
// 已确认列表配置
let tableConfirmedConfig = reactive({
	url: getConfirmedList,
	columns: [
		{
			label: '已确认URL',
			prop: 'resourceStr',
			showOverFlowToolTip: true,
		},
		{
			label: '所属系统',
			prop: 'systemName',
			showOverFlowToolTip: true,
			width: 200,
		},
		{
			label: '所属网端',
			prop: 'systemItName',
			showOverFlowToolTip: true,
			width: 200,
		},
		{
			label: '操作',
			prop: '',
			width: 200,
			operation: [
				{
					text: '确认',
					handler: (scope: anyObj) => handleConfirmResourceAgain(scope.row),
					permi: ['system:itCloud:confirmAgain'],
				},
				{
					text: '删除',
					handler: (scope: anyObj) => handleDeleteConfirmResource(scope.row),
					permi: ['system:itCloud:removeConfirm'],
				},
			],
		},
	],
	// 工具栏
	toolBar: [],
	// 开启复选框
	enableSelection: false,
	// 开启分页
	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	// 加载层
	loading: true,
});
// 黑名单列表配置
let tableBlacklistConfig = reactive({
	url: getBlackList,
	columns: [
		{
			label: '黑名单URL',
			prop: 'confirmedUrl',
			showOverFlowToolTip: true,
		},
		{
			label: '加入黑名单时间',
			prop: 'deleteTime',
			showOverFlowToolTip: true,
		},
		{
			label: '操作',
			prop: '',
			operation: [
				{
					text: '删除',
					handler: (scope: anyObj) => handleDeleteBlackListResource(scope.row),
					permi: ['system:itCloud:removeBlack'],
				},
			],
		},
	],
	// 工具栏
	toolBar: [],
	// 开启复选框
	enableSelection: false,
	// 开启分页
	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	// 加载层
	loading: true,
});
//URL前缀弹窗table
let tableUrlDataConfig = reactive({
	url: getUrlMappingPage,
	columns: [
		{
			label: 'URL前缀',
			prop: 'prefixUrl',
			showOverFlowToolTip: true,
			width: 200,
		},
		{
			label: '原始URL',
			prop: 'oriUrl',
			showOverFlowToolTip: true,
		},
		{
			label: '操作',
			prop: '',
			width: 150,
			operation: [
				{
					text: '确认',
					handler: (scope: anyObj) => handleConfirmResource(scope.row, 1),
					permi: ['system:itCloud:confirm'],
				},
				{
					text: '加入黑名单',
					handler: (scope: anyObj) => handleAddBlackList(scope.row, 1),
					permi: ['system:itCloud:addBlack'],
				},
			],
		},
	],
	// 工具栏
	toolBar: [],
	// 开启复选框
	enableSelection: false,
	// 开启分页
	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	// 加载层
	loading: true,
});
// 未确认列表数据
let tableUnconfirmedData = ref([]);
// 已确认列表数据
let tableConfirmedData = ref([]);
// 黑名单列表数据
let tableBlacklistData = ref([]);
//url列表
let tableUrlData = ref([]);
//Url列表查询参数
let queryUrlDataParams = reactive<anyObj>({});
//未确认查询参数
let queryUnconfirmedParams = reactive<anyObj>({});
//已确认查询参数
let queryConfirmedParams = reactive<anyObj>({});
//黑名单查询参数
let queryBlacklistParams = reactive<anyObj>({});
// 未确认表单
const unConFormOptions = reactive<FormOptionType>([
	{
		type: 'input',
		label: 'URL',
		prop: 'prefixUrl',
		attrs: {
			clearable: true,
		},
	},
]);
const unConFormBtns = reactive<BtnType[]>([
	{
		type: 'primary',
		text: '查询',
		handler: handlerUnconfirmedQuery,
	},
]);
// 确认表单
const conFormOptions = reactive<FormOptionType>([
	{
		type: 'select',
		label: '所属系统',
		prop: 'systemId',
		selectKey: 'value',
		api: {
			name: 'queryAppSystemOptions',
		},
		cascaders: [
			{
				cascadersParams: 'segmentId',
				api: {
					name: 'querySegmentOptions',
				},
			},
		],
	},
	{
		type: 'select',
		prop: 'segmentId',
		label: '所属网端',
	},
	{
		type: 'input',
		label: 'URL',
		prop: 'confirmedUrl',
		attrs: {
			clearable: true,
		},
	},
]);
const conFormBtns = reactive<BtnType[]>([
	{
		type: 'primary',
		text: '查询',
		handler: handlerConfirmedQuery,
	},
]);
// 黑名单表单
const blackFormOptions = reactive<FormOptionType>([
	{
		type: 'input',
		label: 'URL',
		prop: 'confirmedUrl',
		attrs: {
			clearable: true,
		},
	},
]);
const blackFormBtns = reactive<BtnType[]>([
	{
		type: 'primary',
		text: '查询',
		handler: handlerBlacklistQuery,
	},
]);
//系统选择
const systemOptions = ref<any>([]);
//网端选择
const segmentOptions = ref<any>([]);
//业务选择是否禁用
const segmentOptionsDisabled = ref(true);
let selectRow = ref<anyObj>({});
const conForm = ref<any>();
const addBlackFormRef = ref<any>();

onMounted(() => {
	getUnconfirmedList();
});

/** 查询未确认列表 */
function getUnconfirmedList() {
	tableUnconfirmedConfig.loading = true;
	getUnconfirmed(queryUnconfirmedParams)
		.then((response: ApiResponse) => {
			tableUnconfirmedData.value = response.data.records;
			tableUnconfirmedConfig.pagination.total = response.data.total;
			tableUnconfirmedConfig.loading = false;
		})
		.catch((e: any) => {
			tableUnconfirmedConfig.loading = false;
		});
}
/** 查询已确认列表 */
function queryConfirmedList() {
	tableConfirmedConfig.loading = true;
	getConfirmedList(queryConfirmedParams)
		.then((response: ApiResponse) => {
			tableConfirmedData.value = response.data.records;
			tableConfirmedConfig.pagination.total = response.data.total;
			tableConfirmedConfig.loading = false;
		})
		.catch((e: any) => {
			tableConfirmedConfig.loading = false;
		});
}
/** 查询黑名单列表 */
function getBlacklistList() {
	tableBlacklistConfig.loading = true;
	getBlackList(queryBlacklistParams)
		.then((response: ApiResponse) => {
			tableBlacklistData.value = response.data.records;
			tableBlacklistConfig.pagination.total = response.data.total;
			tableBlacklistConfig.loading = false;
		})
		.catch((e: any) => {
			tableBlacklistConfig.loading = false;
		});
}
/*查看url映射*/
function querytUrlMappingPage() {
	tableUrlDataConfig.loading = true;
	getUrlMappingPage(queryUrlDataParams).then((response: ApiResponse) => {
		tableUrlData.value = response.data.records;
		tableUrlDataConfig.pagination.total = response.data.total;
		tableUrlDataConfig.loading = false;
	});
}
/** 未确认搜索按钮操作 */
function handlerUnconfirmedQuery() {
	queryUnconfirmedParams.pageNum = 1;
	getUnconfirmedList();
}
/** 已确认搜索按钮操作 */
function handlerConfirmedQuery() {
	queryConfirmedParams.pageNum = 1;
	queryConfirmedList();
}
/** 黑名单搜索按钮操作 */
function handlerBlacklistQuery() {
	queryBlacklistParams.pageNum = 1;
	getBlacklistList();
}
/*未确认列表勾选事件*/
function handlerSelectionChange(select: any) {
	unconfirmedListSelect.value = select;
}
// 加入黑名单
function handlerAddBlack() {
	const unconfirmedList = unconfirmedListSelect.value;
	if (unconfirmedList.length > 0) {
		let obj = {
			prefixUrls: [],
		} as anyObj;
		obj.prefixUrls = unconfirmedList.map((item: any) => item.prefixUrl);
		proxy.$modal
			.confirm('确定将所选资源加入黑名单吗？', '加入黑名单', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
			.then(() => {
				addBlackList(obj).then((response: ApiResponse | any) => {
					if (response.code === 0) {
						proxy.$modal.msgSuccess('成功加入黑名单！');
						getUnconfirmedList();
					} else {
						proxy.$modal.msgError(response.msg);
					}
				});
			})
			.catch(function () {});
	}
}
/** 未确认列表，弹窗确认按钮操作 */
function handleConfirmResource(row: anyObj, flag: number) {
	let titles = ['按前缀确认', '按原始URL确认', '再次确认'];
	// conForm.value.resetFields();
	type.value = flag;
	selectRow.value = row;
	if (flag === 0) {
		// 按前缀确认
		form.value.url = row.prefixUrl || row.resourceStr;
	} else if (flag === 1) {
		// 按原始URL确认
		form.value.url = row.oriUrl || row.resourceStr;
	} else if (flag === 2) {
		// 在已确认服务资源列表中再次确认资源
		form.value.url = row.oriUrl || row.resourceStr;
	}
	open.value = true;
	title.value = titles[flag];
}
/*已确认列表再次确认按钮*/
function handleConfirmResourceAgain(row: any) {
	handleConfirmResource(row, 2);
}
/*删除已确认服务资源*/
function handleDeleteConfirmResource(row: any) {
	proxy.$modal
		.confirm('确定删除吗？', '删除已确认服务资源', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		})
		.then(() => {
			deleteConfirmedResource(row.id).then((response: ApiResponse | any) => {
				if (response.code === 0) {
					proxy.$modal.msgSuccess('删除成功！');
					queryConfirmedList();
				}
			});
		})
		.catch(() => {});
}
/*删除服务资源黑名单*/
function handleDeleteBlackListResource(row: any) {
	proxy.$modal
		.confirm('确定删除这条服务资源黑名单吗？', '删除服务资源黑名单', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		})
		.then(() => {
			deleteBlackList({ confirmedUrl: row.confirmedUrl }).then((response: ApiResponse | any) => {
				if (response.code === 0) {
					proxy.$modal.msgSuccess('删除成功！');
					getBlacklistList();
				}
			});
		})
		.catch(() => {});
}
/*加入黑名单*/
function handleAddBlackList(row: any, type: number) {
	if (type === 0) {
		// 按前缀加入黑名单
		addBlackForm.url = row.prefixUrl;
	} else if (type === 1) {
		// 按原始URL加入黑名单
		addBlackForm.url = row.oriUrl;
	}
	addBlackTitle.value = type === 0 ? '按前缀加入黑名单' : '按原始URL加入黑名单';
	addBlackOpen.value = true;
}

/*添加黑名单*/
function submitAddBlackForm() {
	unconfirmedLoading.value = true;
	addBlackFormRef.value.validate((valid: any) => {
		if (valid) {
			// 拼接所属网端
			let obj = {
				prefixUrls: [],
			} as anyObj;
			obj.prefixUrls.push(addBlackForm.url.trim());
			if (obj.prefixUrls[0] === '/') {
				proxy.$modal.msgError('无法将 "/" 加入黑名单');
				return;
			}
			let params = {};
			if (type.value === 0) {
				params = {
					prefixUrls: obj.prefixUrls,
				};
			} else if (type.value === 1) {
				params = {
					id: selectRow.value.id,
					// prefixUrls: selectRow.value.prefixUrl,
					originalUrl: selectRow.value.originalUrl,
					prefixUrls: obj.prefixUrls,
					confirmedStatus: 1,
					sourceStatus: 1,
				};
			}
			addBlackList(params)
				.then((response: ApiResponse | any) => {
					if (response.code === 0) {
						addBlackFormRef.value.resetFields();
						addBlackOpen.value = false;
						getUnconfirmedList();
						querytUrlMappingPage();
						proxy.$modal.msgSuccess('完成！');
						unconfirmedLoading.value = false;
					} else {
						unconfirmedLoading.value = false;
						addBlackOpen.value = false;
						proxy.$modal.msgError(response.msg);
					}
				})
				.catch((e: any) => {
					unconfirmedLoading.value = false;
					addBlackOpen.value = false;
					proxy.$modal.msgError(e);
				});
		}
	});
}

/*查看url映射*/
function handleLookUrlMapping(row: any) {
	queryUrlDataParams.pageNum = 1;
	queryUrlDataParams.prefixUrl = row.prefixUrl;
	querytUrlMappingPage();
	urlListOpen.value = true;
}
/** 确认提交按钮 */
function submitConfirmResourceForm() {
	conForm.value.validate((valid: any) => {
		if (valid) {
			// 拼接所属网端
			let segmentIds = form.value.segmentId.join(',');
			let url = form.value.url.trim();
			let systemId = form.value.system;
			if (url.lastIndexOf('/') === url.length - 1) {
				proxy.$modal.msgError('url不能以"/"号结尾');
				return;
			}
			let params = {};
			if (type.value === 0) {
				params = {
					confirmedUrl: url, // 编辑后的前缀
					confirmedStatus: 0, // 0: 按前缀确认
					systemId: systemId, // 选择的系统id
					segmentId: segmentIds, // 选择的网端id，最多两个，用逗号隔开
				};
			} else if (type.value === 1) {
				params = {
					id: selectRow.value.id,
					prefixUrl: selectRow.value.prefixUrl,
					originalUrl: selectRow.value.originalUrl,
					confirmedUrl: url,
					confirmedStatus: 1,
					systemId: systemId,
					segmentId: segmentIds,
				};
			} else {
				// 前端简单校验是否选择了相同的系统和网端
				let segmentId = form.value.segmentId;
				for (let i = 0; i < segmentId.length; i++) {
					if (segmentId[i] === selectRow.value.systemItId) {
						proxy.$msgError('所属系统和所属网端不能相同');
						return;
					}
				}
				params = {
					id: selectRow.value.id, //id
					confirmedUrl: url, // 编辑后的确认url
					systemId: systemId, // 选择的系统id
					segmentId: segmentIds, // 选择的网端id，最多两个，用逗号隔开
				};
			}
			unconfirmedLoading.value = true;
			if (type.value === 0 || type.value === 1) {
				confirmResource(params).then((response: ApiResponse | any) => {
					if (response.code === 0) {
						proxy.$modal.msgSuccess('确认完成！');
					} else {
						proxy.$modal.msgError(response.msg);
					}
					reset();
					open.value = false;
					getUnconfirmedList();
					querytUrlMappingPage();
					unconfirmedLoading.value = false;
				});
			} else {
				confirmResourceAgain(params).then((response: ApiResponse | any) => {
					if (response.code === 0) {
						reset();
						proxy.$modal.msgSuccess('确认完成！');
						open.value = false;
						queryConfirmedList();
						unconfirmedLoading.value = false;
					} else {
						proxy.$modal.msgError(response.msg);
						open.value = false;
						unconfirmedLoading.value = false;
					}
				});
			}
		}
	});
}
// 取消按钮
function cancel() {
	open.value = false;
	reset();
}
function urlListOpenCancel() {
	urlListOpen.value = false;
}
/** 重置按钮操作 */
function reset() {
	conForm.value.resetFields();
}
function change(e: any) {
	// proxy.$forceUpdate();
}
function handleClick(tab: string) {
	switch (tab) {
		case 'unconfirmed':
			getUnconfirmedList();
			return;
		case 'confirmed':
			queryConfirmedList();
			return;
		case 'blacklist':
			getBlacklistList();
			return;
	}
}
function handleSelectChange(value: any) {
	// proxy.$forceUpdate();
	form.value.segmentId = undefined;
	const selectItem: any = systemOptions.value.find((s: anyObj) => s.value === value);
	console.log(selectItem, systemOptions.value, value, 'selectItem');

	querySegmentOptions(value).then((res) => {
		segmentOptions.value = res.data;
	});
	segmentOptionsDisabled.value = false;
}

queryAppSystemOptions().then((res: ApiResponse) => {
	systemOptions.value = res.data;
});
</script>
